new Vue({
  el: '#app',
  data() {
    return {
      loading: false,
      messageList: [],
      dateRange: null,
      filterForm: {
        title: '',
        target_type: null,
        status: null,
        priority: null,
        start_time: null,
        end_time: null
      },
      pagination: {
        page: 1,
        page_size: 10,
        total: 0
      }
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.loading = true;
      const url = 'http://localhost:3000/api/admin/messages';

      const params = {
        page: this.pagination.page,
        page_size: this.pagination.page_size,
        ...this.filterForm
      };

      // 构建查询字符串
      const queryString = Object.keys(params)
      .filter(key => params[key] !== null && params[key] !== undefined && params[key] !== '')
      .map(key => `${ encodeURIComponent(key) }=${ encodeURIComponent(params[key]) }`)
      .join('&');

      window.we.fetch(`${ url }?${ queryString }`)
      .then(data => {
        const { code, data: responseData } = data;
        if(code === 0) {
          this.messageList = responseData.list;
          this.pagination.total = responseData.total;
        } else {
          this.$message.error('获取消息列表失败');
        }
      })
      .catch(error => {
        console.error('获取消息列表出错:', error);
        this.$message.error('获取消息列表出错');
      })
      .finally(() => {
        this.loading = false;
      });
    },

    handleSearch() {
      if(this.dateRange) {
        this.filterForm.start_time = this.dateRange[0];
        this.filterForm.end_time = this.dateRange[1];
      } else {
        this.filterForm.start_time = null;
        this.filterForm.end_time = null;
      }
      this.pagination.page = 1;
      this.fetchData();
    },

    handleReset() {
      this.$refs.filterForm.resetFields();
      this.dateRange = null;
      this.filterForm.start_time = null;
      this.filterForm.end_time = null;
      this.pagination.page = 1;
      this.fetchData();
    },

    handleSizeChange(val) {
      this.pagination.page_size = val;
      this.fetchData();
    },

    handleCurrentChange(val) {
      this.pagination.page = val;
      this.fetchData();
    },

    handleAdd() {
      // 跳转到消息编辑页面
      window.location.href = '/edit.html';
    },

    handleEdit(id) {
      // 跳转到消息编辑页面，带上ID参数
      window.location.href = `/edit.html?id=${ id }`;
    },

    handleDelete(id) {
      this.$confirm('确认删除该消息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = `http://localhost:3000/api/admin/messages/${ id }`;

        window.we.fetch(`${ url }?${ queryString }`, {
          method: 'DELETE',
        })
        .then(data => {
          const { code } = data;
          if(code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchData();
          } else {
            this.$message.error('删除失败');
          }
        })
        .catch(error => {
          console.error('删除消息出错:', error);
          this.$message.error('删除消息出错');
        });
      }).catch(() => {
        // 取消删除
      });
    },

    handlePublish(id) {
      this.$confirm('确认发布该消息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        const url = `http://localhost:3000/api/admin/messages/${ id }/publish`;
        window.we.fetch(url, {
          method: 'POST'
        })
        .then(data => {
          const { code } = data;
          if(code === 0) {
            this.$message({
              type: 'success',
              message: '发布成功!'
            });
            this.fetchData();
          } else {
            this.$message.error('发布失败');
          }
        })
        .catch(error => {
          console.error('发布消息出错:', error);
          this.$message.error('发布消息出错');
        });
      }).catch(() => {
        // 取消发布
      });
    },

    formatTimestamp(timestamp) {
      if(!timestamp) {
        return '--';
      }
      const date = new Date(timestamp);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      });
    },

    formatNotificationType(type) {
      const typeMap = {
        'app_popup': 'App弹框',
        'app_push': 'App推送'
      };
      return typeMap[type] || type;
    },

    getStatusClass(status) {
      const statusMap = {
        1: 'draft',
        2: 'published',
        3: 'inactive',
        4: 'published',
        5: 'expired'
      };
      return statusMap[status] || 'draft';
    },

    getPriorityClass(priority) {
      const priorityMap = {
        1: 'urgent',
        2: 'high',
        3: 'medium',
        4: 'low'
      };
      return priorityMap[priority] || 'medium';
    }
  }
});
